﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace TicketsWizards
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        Bitmap bitmap;

        private void btnToOcr_Click(object sender, EventArgs e)
        {
            GetCode();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            getImg();

        }

        private void getImg()
        {
            //自动加载要识别的图片
            try
            {
                WebRequest request = WebRequest.Create("https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=randp");
                WebResponse response = request.GetResponse();
                Stream st = response.GetResponseStream();
                bitmap = (Bitmap)Bitmap.FromStream(st);
                UnCodebase ud = new UnCodebase(bitmap);
                bitmap = ud.GrayByPixels();
                ud.ClearNoise(128, 2);
                bitmap = ud.ReSetBitMap();

                pictureBox1.Image = bitmap;
            }
            catch (Exception ex)
            {
            }
            finally { }
        }

        private void GetCode()
        {
            try
            {
                tessnet2.Tesseract ocr = new tessnet2.Tesseract();//声明一个OCR类

                ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
                ocr.Init(Application.StartupPath + @"\Eng", "eng", false);

                //ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); //设置识别变量，当前只能识别数字和字母。
                //ocr.Init(Application.StartupPath + "\\tmpe", "eng", false); //应用当前语言包。注，Tessnet2是支持多国语的。语言包下载链接：http://code.google.com/p/tesseract-ocr/downloads/list
                List<tessnet2.Word> result = ocr.DoOCR(bitmap, Rectangle.Empty);//执行识别操作
                string code = result[0].Text;
                textBox1.Text = code;
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
            finally { }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            getImg();
        }
    }
}
